﻿using Saber.Infrastructure;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using UsnOperation;

namespace Saber.Plugin.NtfsSearch.QueryEngine
{
    public class FileAndDirectoryEntry
    {
        public UInt64 FileReferenceNumber { get; }

        public UInt64 ParentFileReferenceNumber { get; }

        public string FileName { get; }

        public bool IsFolder { get; }

        public string Path { get;  }

        public string FullFileName
        {
            get
            {
                return string.Concat(this.Path, "\\", this.FileName);
            }
        }


        public FileAndDirectoryEntry(UsnEntry usnEntry, string path)
        {
            this.FileReferenceNumber = usnEntry.FileReferenceNumber;
            this.ParentFileReferenceNumber = usnEntry.ParentFileReferenceNumber;
            this.FileName = usnEntry.FileName;
            this.IsFolder = usnEntry.IsFolder;
            this.Path = path;
        }


        private int Score(string query)
        {
            var score1 = StringMatcher.Score(FileName, query);
            var score2 = StringMatcher.ScoreForPinyin(FileName, query);
            //var score3 = StringMatcher.Score(FullFileName, query);
            //var score4 = StringMatcher.ScoreForPinyin(FullFileName, query);
            //var score5 = StringMatcher.Score(ExecutableName, query);
            var score = new[] { score1, score2 }.Max();
            return score;
        }


        public Result Result(string query, IPublicAPI api)
        {

            var score = Score(query);
            if (score <= 0)
            {
                return null;
            }

            var result = new Result
            {
                Title=FileName,
                SubTitle = FullFileName,
                IcoPath = FullFileName,
                Score = score,
                ContextData = this,
                Action = e =>
                {
                    var info = new ProcessStartInfo
                    {
                        FileName = FileName,
                        WorkingDirectory = Path
                    };
                    var hide = Main.StartProcess(info);
                    return hide;
                }
            };

            //if (Description.Length >= Name.Length &&
            //    Description.Substring(0, Name.Length) == Name)
            //{
            //    result.Title = FileName;
            //}
            //else if (!string.IsNullOrEmpty(Description))
            //{
            //    result.Title = $"{Name}: {Description}";
            //}
            //else
            //{
            //    result.Title = Name;
            //}

            return result;
        }
    }
}
